package com.cskaoyan.controller;

import com.cskaoyan.bean.AdminInfoBean;
import com.cskaoyan.bean.BaseRespVo;
import com.cskaoyan.bean.InfoData;
import com.cskaoyan.bean.LoginUserData;
import com.cskaoyan.bean.pojo.MarketAdmin;
import com.cskaoyan.bean.vo.AuthLoginVO;
import com.cskaoyan.service.AuthService;
import com.cskaoyan.shiro.MallToken;
import com.cskaoyan.utils.Md5Util;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Map;

//shiro整合之后，在做具体的开发
//响应结果都是JSON，Controller组件上我们都用@RestController注解
@RestController
@RequestMapping("admin/auth")
public class AuthController {

    @Autowired
    AuthService authService;

    /**
     * 如果参数比较少，类型比较简单的话，使用map来接收也可以
     */
    @PostMapping("login")
    public BaseRespVo<LoginUserData> login(@RequestBody Map map) throws Exception {
        String username = (String)map.get("username");
        String password = (String)map.get("password");

        MallToken adminToken = new MallToken(username, password, "admin");
        Subject subject = SecurityUtils.getSubject();
        subject.login(adminToken);

        LoginUserData loginUserData = authService.authLogin(username,password);
        Serializable id = subject.getSession().getId();
        loginUserData.setToken((String)id);

        return BaseRespVo.ok(loginUserData);
    }

    @PostMapping("logout")
    public BaseRespVo logout() {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return BaseRespVo.ok();
    }



    @RequestMapping("info")
    public BaseRespVo info(String token) {

        Subject subject = SecurityUtils.getSubject();
        MarketAdmin admin = (MarketAdmin) subject.getPrincipal();
        /*System.out.println(subject.isAuthenticated());
        System.out.println(subject.getSession().getId());*/
        if(admin!=null){
            InfoData infoData = authService.getInfo(admin);
            return BaseRespVo.ok(infoData);
        }else{
            return BaseRespVo.fail(501);
        }

    }
}
